package com.chenlehao.utils;

import com.chenlehao.customExceptions.AppException;
import com.chenlehao.customExceptions.AppExceptionCodeMsg;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class jwt {
    @Autowired
    private token tokens;

    // 获取token
    public String getJwt(int id, String username) {
        log.info("密钥{}", tokens.getSecretKey());
        log.info("期限{}", tokens.getTimer());
        Map<String, Object> claims = new HashMap<>();
        // 设置自定义内容
        claims.put("id", id);
        claims.put("username", username);
        // 创建token
        String token = Jwts.builder()
                .setClaims(claims) // 自定义内容(载荷)
                .signWith(SignatureAlgorithm.HS256, tokens.getSecretKey()) // 签名算法和密钥
                .setExpiration(new Date(System.currentTimeMillis() + tokens.getTimer() * 1000)) // 有效期
                .compact();
        return token;
    }

    // 解析token
    public Claims parseJwt(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(tokens.getSecretKey())
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            throw new AppException(AppExceptionCodeMsg.NOT_LOGIN);
        }
        // Claims就是解析出来创建token时的自定义内容
        log.info("id:{}, 用户名:{}", claims.get("id"), claims.get("username"));
        return claims;
    }
}
